package com.bw.mine.ui

import android.view.View
import androidx.lifecycle.ViewModelProviders
import com.bw.common.BaseApplication
import com.bw.common.common.ConstantValue
import com.bw.common.encry.AESUtils
import com.bw.common.utils.SharedPreferenceDelegate
import com.bw.common.utils.UserUtils
import com.bw.mine.databinding.ActivityLoginBinding
import com.bw.mine.intent.LoginIntent
import com.bw.mine.model.service.LoginModel
import com.bw.mine.state.LoginState
import com.bw.mvicore.ui.BaseMVIActivity
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class LoginActivity : BaseMVIActivity() {
    private lateinit var binding: ActivityLoginBinding
    private lateinit var model:LoginModel
    override fun generateModel() {
        model= ViewModelProviders.of(this).get(LoginModel::class.java)
    }

    override fun releaseRes() {

    }

    override fun generateContentView(): View {
        binding = ActivityLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initData() {

    }

    override fun initEvent() {
        binding.btnMineLoginLogin.setOnClickListener {
            val username = binding.etMineLoginUsername.text.trim().toString()
            val password = binding.etMineLoginPwd.text.trim().toString()
            if (username.isBlank()){
                showMsg("请输入用户名")
                return@setOnClickListener
            }
            if (password.isBlank()){
                showMsg("请输入密码")
                return@setOnClickListener
            }

            generateLifeCycleLaunch {
                model.intents.send(LoginIntent.FinalLoginIntent(username,password))
            }
        }
        binding.tvLoginRegister.setOnClickListener {
            route(RegisterActivity::class.java)
        }
    }

    /**
     * 登录的token
     */
    private var token:String by SharedPreferenceDelegate<String>(
        BaseApplication.getApplicationContext(),
        ConstantValue.SP_NAME,
        ConstantValue.SP_KEY_TOKEN,"")
    override fun handleState() {
        generateLifeCycleLaunch {
            model.state.collect{
                when(it){
                    is LoginState.LoginDefaultState->{}
                    is LoginState.LoginSuccessState->{
                        withContext(Dispatchers.Main){
                            //对获取到的token进行对称加密然后通过属性委托存储到SP
                            val cryptToken = AESUtils.getInstance().encrypt(it.entity.token,com.bw.net.common.ConstantValue.AESKEY)
                            token=cryptToken
                            it.entity.password=binding.etMineLoginPwd.text.toString().trim()
                            //使用gson序列化UserEntity到SP
                            UserUtils.saveUser(Gson().toJson(it.entity))
                            showMsg("登录成功")
                        }
                        closeThiz()
                    }
                    is LoginState.LoginFailedState->{
                        withContext(Dispatchers.Main){
                            showMsg("登录失败，info:${it.throwable.message}")
                        }
                    }
                }
            }
        }
    }
}